package com.kuangjia.scenic_spot_ticket.controller;

import com.kuangjia.scenic_spot_ticket.common.Result;
import com.kuangjia.scenic_spot_ticket.entity.ScenicSpot;
import com.kuangjia.scenic_spot_ticket.service.ScenicSpotService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/scenic-spots")
public class ScenicSpotController {
    @Autowired
    private ScenicSpotService scenicSpotService;

    @GetMapping
    public Result<List<ScenicSpot>> list() {
        return Result.success(scenicSpotService.list());
    }

    @PostMapping
    public Result<Boolean> add(@RequestBody ScenicSpot spot) {
        return Result.success(scenicSpotService.save(spot));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody ScenicSpot spot) {
        return Result.success(scenicSpotService.updateById(spot));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            boolean removed = scenicSpotService.removeById(id);
            System.out.println("删除景点id=" + id + "，结果：" + removed);
            if (!removed) {
                return Result.error("删除失败，id不存在或有关联数据");
            }
            return Result.success(true);
        } catch (Exception e) {
            System.out.println("删除景点id=" + id + "，异常：" + e.getMessage());
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    public Result<Page<ScenicSpot>> page(@RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "10") int size,
                                         @RequestParam(required = false) String keyword) {
        LambdaQueryWrapper<ScenicSpot> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(ScenicSpot::getName, keyword);
        }
        Page<ScenicSpot> spotPage = scenicSpotService.page(new Page<>(page, size), wrapper);
        return Result.success(spotPage);
    }
} 